# encoding = utf-8
class ProductsController < ApplicationController
  
  before_filter :authenticate_admin!, :only => [:new, :create, :list, :edit, :update, :delete]

  def index
    @products = Product.order('stock desc').paginate :page => params[:page], :per_page => PAGE_SIZE
    @types = Type.all
  end

  def types
    @products = Product.where(:type_id => params[:id]).order('created_at desc').paginate :page => params[:page], :per_page => PAGE_SIZE
    @types = Type.all
    render :action => :index
  end
  
#  == admin ====================================================================

  def new
    @product = Product.new
    @types = Type.all
    @action = {:action => 'create'}
    @action_title = '添加新产品'
    render :layout => 'admins'
  end

  def create
    @product = Product.new(params[:product])
    
    if @product.save
      flash[:success] = '添加产品成功'
      redirect_to :action => "list"
    else
      @types = Type.all
      @action = {:action => 'create'}
      @action_title = '添加新产品'
      flash[:error] = @product.errors
      render :layout => 'admins', :action => 'new'
    end
  end

  def show
    @product = Product.find(params[:id])
    @types = Type.all
  end
  
  def list
    @products = Product.order('created_at desc').paginate :page => params[:page], :per_page => PAGE_SIZE
    render :layout => 'admins'
  end

  def edit
    @product = Product.find(params[:id])
    @types = Type.all
    @action = {:action => 'update', :id => @product.id}
    @action_title = '编辑产品'
    render :layout => 'admins', :action => 'new'
  end

  def update
    if params[:product][:avatar].blank?
      params[:product][:avatar] = Product.find(params[:id]).avatar
    end
    product = Product.update(params[:id], params[:product])
    if product
      flash[:success] = '产品更新成功'
    else
      flash[:error] = '产品更新失败'
    end
    redirect_to :action => "list"
  end

  def delete
    product = Product.find(params[:id])
    if product.destroy
      flash[:success] = '产品删除成功'
    end
    redirect_to :action => "list"
  end
  
end
